package org.smoke.controllers;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.paramresolver.ParamMetaData;
import net.paoding.rose.web.paramresolver.ParamResolver;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.smoke.bean.UserToken;
import org.smoke.constants.ServerConstants;
import org.smoke.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.Cookie;

/**
 * @author guoyuchuan on 2014/11/3.
 */
public class TokenResolver implements ParamResolver {

    private static final Logger LOG = LogManager.getLogger(TokenResolver.class);

    private static UserToken INVALID_TOKEN = new UserToken(
            StringUtils.EMPTY, -1 , -1
    );

    @Autowired
    private UserService userService;

    @Override
    public boolean supports(ParamMetaData metaData) {
        return "token".equals(metaData.getParamName());
    }

    @Override
    public Object resolve(Invocation inv, ParamMetaData metaData) throws Exception {
        String token = inv.getParameter("token");
        token = StringUtils.isBlank(token) ? tokenFromCookie(inv) : token;
        if (StringUtils.isBlank(token)) {
            LOG.warn(String.format("class: [TokenResolver] msg: [User Token Is Blank]"));
            return INVALID_TOKEN;
        }
        return userService.getUserToken(token);
    }

    private String tokenFromCookie(Invocation inv) {
        Cookie[] cookies = inv.getRequest().getCookies();
        if (cookies == null || cookies.length == 0) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (ServerConstants.COOKIE_NAME.equals(cookie.getName())) {
                return cookie.getValue();
            }
        }
        return null;
    }

}
